package com.jyy.prefabricated.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jyy.prefabricated.common.AjaxResult;
import com.jyy.prefabricated.dto.BatchDto;
import com.jyy.prefabricated.dto.Pageable;
import com.jyy.prefabricated.entity.*;
import com.jyy.prefabricated.enums.OrderTypeEnum;
import com.jyy.prefabricated.mapper.CourseCategoryMapper;
import com.jyy.prefabricated.mapper.StudentCourseMapper;
import com.jyy.prefabricated.mapper.TrainingOrganizationStockMapper;
import com.jyy.prefabricated.mapper.ViewLogMapper;
import com.jyy.prefabricated.service.CourseService;
import com.jyy.prefabricated.utils.OrderUtil;
import com.jyy.prefabricated.utils.UserSessionUtil;
import com.jyy.prefabricated.utils.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * 课程
 *
 * @version 1.0.0
 * @author: zjj
 */
@Slf4j
@RequestMapping("/api")
@RestController
public class CourseController {

    @Resource
    private CourseService courseService;
    @Resource
    private CourseCategoryMapper courseCategoryMapper;
    @Resource
    private TrainingOrganizationStockMapper trainingOrganizationStockMapper;
    @Resource
    private UserUtils userUtils;
    @Resource
    private ViewLogMapper viewLogMapper;
    @Resource
    private StudentCourseMapper studentCourseMapper;

    /**
     * 新增课程
     *
     * @param course
     * @return
     */
    @PostMapping("/course")
    public AjaxResult insert(@Valid @RequestBody CourseWithBLOBs course) throws Exception {
        log.info("Rest request to insert course:{}", course);
        int id = courseService.insert(course);
        CourseWithBLOBs result = courseService.selectById(id);
        return AjaxResult.success(result);
    }

    /**
     * 更新课程
     *
     * @param course
     * @return
     */
    @PutMapping("/course")
    public AjaxResult update(@Valid @RequestBody CourseWithBLOBs course) throws Exception {
        log.info("Rest request to update course:{}", course);
        courseService.update(course);
        CourseWithBLOBs result = courseService.selectById(course.getId());
        return AjaxResult.success(result);
    }

    /**
     * 批量更新课程状态
     *
     * @param dto
     * @return
     */
    @PutMapping("/course-batch")
    public AjaxResult update(@Valid @RequestBody BatchDto dto) {
        log.info("Rest request to batch-update course:{}", dto);
        courseService.batchUpdateStatus(dto);
        return AjaxResult.success();
    }

    /**
     * 批量删除课程
     *
     * @param dto
     * @return
     */
    @DeleteMapping("/course-batch")
    public AjaxResult deleteById(@RequestBody BatchDto dto) {
        log.info("Rest request to batch-delete course by id:{}", dto);
        int row = courseService.batchDelete(dto);
        if (row > 0) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error();
        }
    }

    /**
     * 查询课程详情
     *
     * @param id
     * @return
     */
    @GetMapping("/course/{id}")
    public AjaxResult selectById(@PathVariable Integer id) {
        log.info("Rest request to find course by id:{}", id);
        CourseWithBLOBs result = courseService.selectById(id);
        //    SysUser user = userUtils.getCurrentUser();

        SysUser user = null;
        String token = UserSessionUtil.resolveToken();
        if (StringUtils.isNotBlank(token)) {
            user = userUtils.getCurrentUser();
        }
        if (user != null) {
            //判断学员购买课程包后，章节视频是否看完
            if (user.getStudent() != null) {
                if (result != null && result.getFiles() != null && result.getFiles().size() > 0) {

                    for (CourseFile courseFile : result.getFiles()) {
                        ViewLog viewLog = new ViewLog();
                        viewLog.setSessionId(user.getStudent().getId().toString());
                        viewLog.setVideoId(courseFile.getPath());
                        List<ViewLog> viewLogList = viewLogMapper.queryAll(viewLog);
                        if (viewLogList != null && viewLogList.size() > 0) {
                            if (viewLogList.get(0).getPlayDuration() + 10 >= Integer.valueOf(viewLogList.get(0).getDuration())
                                    || Integer.valueOf(viewLogList.get(0).getCurrentTimes() + 10) >= Integer.valueOf(viewLogList.get(0).getDuration())) {
                                courseFile.setIsView(true);
                            }
                        }
                    }
                }
            }
            //判断是否已经购买该课程
            if (user.getStudent() != null) {
                int count = studentCourseMapper.selectByStudentIdAndCourseId(id, user.getStudent().getId());
                if (count > 0) {
                    result.setIsBuy(true);
                }
            }
            if (user.getTrainingOrganization() != null) {
                TrainingOrganizationStock trainingOrganizationStock = trainingOrganizationStockMapper.selectByTrainingOrganizationIdProductIdAndType(user.getTrainingOrganization().getId(), id, OrderTypeEnum.COURSE.getValue());
                if (trainingOrganizationStock != null) {
                    result.setIsBuy(true);
                }
            }
        }
        return AjaxResult.success(result);
    }

    /**
     * 删除课程
     *
     * @param id
     * @return
     */
    @DeleteMapping("/course/{id}")
    public AjaxResult deleteById(@PathVariable Integer id) {
        log.info("Rest request to delete course by id:{}", id);
        int row = courseService.delete(id);
        if (row > 0) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error();
        }
    }

    /**
     * 后台分页查询课程列表
     *
     * @param courseName 课程名称
     * @param lecturer   导师
     * @param type       课程类型
     * @param categoryId 课程分类id
     * @param status     课程状态
     * @param ascColumn  课程升序排序字段
     * @param descColumn 课程降序排序字段
     * @param pageable   分页信息
     * @return
     */
    @GetMapping("/course")
    public AjaxResult selectByParams(@RequestParam(required = false, defaultValue = "") String courseName, @RequestParam(required = false, defaultValue = "") String lecturer, @RequestParam(required = false) Integer type, @RequestParam(required = false) Integer plateId, @RequestParam(required = false) Boolean recommend, @RequestParam(required = false) Integer categoryId, @RequestParam(required = false) Integer status, @RequestParam(required = false, defaultValue = "") String ascColumn, @RequestParam(required = false, defaultValue = "") String descColumn, Pageable pageable) {
        String orderStr = OrderUtil.genOrderStr(ascColumn, descColumn);
        log.info("Rest request to find course by params type:{},courseName:{},categoryId:{},lecturer:{},status:{},orderStr:{}", type, courseName, categoryId, lecturer, status, orderStr);
        List<Integer> categoryIds = courseService.selectDeepCategoryIds(categoryId);
        PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<CourseWithBLOBs> course = courseService.selectDeepByParams(type, plateId, recommend, courseName, categoryIds, lecturer, status, orderStr);
        PageInfo<CourseWithBLOBs> result = new PageInfo<>(course);
        return AjaxResult.success(result);
    }

    /**
     * 移动端分页查询课程
     *
     * @param courseName 课程名称
     * @param lecturer   导师
     * @param type       课程类型
     * @param categoryId 课程分类id
     * @param status     课程状态
     * @param top        是否置顶
     * @param ascColumn  课程升序排序字段
     * @param descColumn 课程降序排序字段
     * @param pageable   分页信息
     * @param sortStatus 排序状态（1、最新、2、最热、3、免费）
     * @return
     */
    @GetMapping("/course-mobile")
    public AjaxResult selectWithPackageByParamsDeep(@RequestParam(required = false, defaultValue = "") String courseName, @RequestParam(required = false, defaultValue = "") String lecturer, @RequestParam(required = false) Integer type, @RequestParam(required = false) Integer plateId, @RequestParam(required = false) Boolean recommend, @RequestParam(required = false) Integer categoryId, @RequestParam(required = false) Integer status, @RequestParam(required = false) Boolean top, @RequestParam(required = false, defaultValue = "") String ascColumn, @RequestParam(required = false, defaultValue = "") String descColumn, @RequestParam(required = false) Integer sortStatus, @RequestParam(required = false) Integer levelIndex, Pageable pageable) {
        String orderStr = OrderUtil.genOrderStr(ascColumn, descColumn);
        log.info("Rest request to find course by params type:{},courseName:{},categoryId:{},lecturer:{},status:{},orderStr:{}", type, courseName, categoryId, lecturer, status, orderStr);
        //List<Integer> categoryIds = courseService.selectDeepCategoryIds(categoryId);
        List<Integer> categoryIds = new ArrayList<>();
        if (categoryId != null) {
            if (levelIndex != null && levelIndex == 0) {
                categoryIds = courseService.selectDeepCategoryIds(categoryId);
                for (int i = 0; i < categoryIds.size(); i++) {
                    if (categoryIds.get(i).equals(categoryId)) {
                        categoryIds.remove(i);
                    }
                }
            } else {
                categoryIds.add(categoryId);
            }


        } else {
            List<CourseCategory> categories = courseCategoryMapper.selectByParams(null, 0 ,null);
            for (CourseCategory courseCategory : categories) {
                categoryIds.add(courseCategory.getId());
            }
        }

        PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());

        if (categoryIds == null || categoryIds.size() <= 0) {
            List<Course> courses = new ArrayList<>();
            PageInfo<Course> result = new PageInfo<>(courses);
            return AjaxResult.success(result);
        }
        List<Course> courses = courseService.selectWithPackageByParamsDeep(type, plateId, recommend, courseName, categoryIds, lecturer, status, top, orderStr, sortStatus);
        PageInfo<Course> result = new PageInfo<>(courses);
        return AjaxResult.success(result);
    }


    /**
     * 查询课程列表不分页
     *
     * @param courseName 课程名称
     * @param lecturer   导师
     * @param type       课程类型
     * @param categoryId 课程分类id
     * @param status     课程状态
     * @param ascColumn  课程升序排序字段
     * @param descColumn 课程降序排序字段
     * @return
     */
    @GetMapping("/course-list")
    public AjaxResult selectByParams(@RequestParam(required = false, defaultValue = "") String courseName, @RequestParam(required = false, defaultValue = "") String lecturer, @RequestParam(required = false) Integer type, @RequestParam(required = false) Integer plateId, @RequestParam(required = false) Boolean recommend, @RequestParam(required = false) Integer categoryId, @RequestParam(required = false) Integer status, @RequestParam(required = false, defaultValue = "") String ascColumn, @RequestParam(required = false, defaultValue = "") String descColumn) {
        String orderStr = OrderUtil.genOrderStr(ascColumn, descColumn);
        log.info("Rest request to find course by params type:{},courseName:{},categoryId:{},lecturer:{},status:{},orderStr:{}", type, courseName, categoryId, lecturer, status, orderStr);
        List<Integer> categoryIds = courseService.selectDeepCategoryIds(categoryId);
        List<CourseWithBLOBs> result = courseService.selectDeepByParams(type, plateId, recommend, courseName, categoryIds, lecturer, status, orderStr);
        return AjaxResult.success(result);
    }


    /**
     * 查询课程详情通过resourceId
     *
     * @param resourceId
     * @return
     */
    @GetMapping("/course-resource/{resourceId}")
    public AjaxResult selectByResourceId(@PathVariable String resourceId) {
        log.info("Rest request to find course by resourceId:{}", resourceId);
        Course result = courseService.selectByResourceId(resourceId);
        return AjaxResult.success(result);
    }

}
